<script setup lang="ts">
import { computed, onMounted } from "vue";

import useCustomerStore from "@src/store/customerStore";
import { useRoute } from "vue-router";

import Chat from "@src/components/views/HomeView/Chat/Chat.vue";
import Navigation from "@src/components/views/HomeView/Navigation/Navigation.vue";
import Sidebar from "@src/components/views/HomeView/Sidebar/Sidebar.vue";
import NoChatSelected from "@src/components/states/empty-states/NoChatSelected.vue";
import Loading3 from "@src/components/states/loading-states/Loading3.vue";
import FadeTransition from "@src/components/ui/transitions/FadeTransition.vue";
import router from "@src/router";
import { useCookies } from "vue3-cookies";
import useStore from "@src/store/store";
import { getCustomerBaseInfo } from "@src/network/api";
import error from "@src/components/states/error-states/error.vue";
import defaults from "@src/store/defaults";

const customerStore = useCustomerStore();
const store = useStore();
const route = useRoute();

//获取当前用户id
const {cookies} = useCookies();
let customerid = route.params.customerId as string
const websiteId = route.params.websiteId as string
if(!websiteId) {
  store.error = true;
}
if(!customerid){
  customerid = cookies.get("aivo-user");
}else{
  customerStore.$patch({
    infoId:customerid
  })
}
if(!customerid){
  customerid = crypto.randomUUID()
  cookies.set("aivo-user",customerid);
}
customerStore.customerId = customerid;
console.log("get uuid" + customerStore.customerId)

//请求基础数据
getCustomerBaseInfo(websiteId,customerid).then((res)=>{
  console.log(res)
  customerStore.$patch({
    services:res.services,
    website:res.website,
    customer:res.customer,
    conversations:res.conversation,
  })
  store.status = "success"

  //塞一条访问数据
  const keys = Object.keys(res.conversation);
  keys.sort(function(a,b){return parseInt(a) - parseInt(b);});
  const lastKey = keys[keys.length - 1];
  const lastConversation = res.conversation[lastKey];
  let id = 0.5;
  if(lastConversation) {
    id = lastConversation.id + 0.5;
  }
  const formattedCurrentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
  if (customerStore.website?.id == 5) {
    customerStore.addConversation({
      id: id,
      website_id: res.website.id,
      customer_id: res.customer.id,
      service_id: res.customer.current_service_id,
      message: `
  平台快送（多伦多）：不同区域免邮门槛不同，不到免邮门槛，收取配送费$7.99。点击查看各区域免邮门槛https://foodyie.ca/pages/paymentanddelivery

  配送时间：当日15:00前的订单，晚上17:00~22:00配送。

  特殊要求请联系客服<a href="tel://6472739168" class="text-indigo-500 dark:text-indigo-300">647-273-9168</a>节假日配送时间另作通知。

  *订单重量超过20磅，每磅加收$0.5。
  *配送中的订单不予取消。
  *配送时间可能因天气等外力因素有所变化。
      `,
      message_round: 's2c',
      create_time: formattedCurrentTime,
      sender: {
        id: res.customer.id,
        name: res.customer.customer_session,
        head_url: ''
      },
      type: "text",
      relation_id:customerStore.conversationRelation?.id ?? 0
    });
    }else if(customerStore.website?.id == 6){
      customerStore.addConversation({
      id: id,
      website_id: res.website.id,
      customer_id: res.customer.id,
      service_id: res.customer.current_service_id,
      message: `
  DNY123欢迎您

  请问有什么可以帮助？
      `,
      message_round: 's2c',
      create_time: formattedCurrentTime,
      sender: {
        id: res.customer.id,
        name: res.customer.customer_session,
        head_url: ''
      },
      type: "text",
      relation_id:customerStore.conversationRelation?.id ?? 0
    });
    }
})


// the active chat component or loading component.
const activeChatComponent = computed((): any => {
  if (store.error) {
    return error;
  }else if (store.status === "loading") {
    return Loading3;
  } else {
    return Chat;
  }
});
</script>

<template>
  <KeepAlive>
    <div
      class="xs:relative md:static h-full flex xs:flex-col md:flex-row overflow-hidden"
    >
      <!--chat-->
      <div
        id="mainContent"
        class="xs:absolute xs:z-10 md:static grow h-full xs:w-full md:w-fit scrollbar-hidden bg-white dark:bg-gray-800 transition-all duration-500"
        :class="
          ['xs:left-[0px]', 'xs:static']
        "
        role="region"
      >
        <FadeTransition name="fade" mode="out-in">
          <component
            :is="activeChatComponent"
            key="onlyoneconvsation"
          />
        </FadeTransition>
      </div>
    </div>
  </KeepAlive>
</template>
